package com.java.com.syun.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class AIOServer {

    public static void main(String[] args) throws IOException, InterruptedException {
        AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress("127.0.0.1", 9002));
        server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
            @Override
            public void completed(AsynchronousSocketChannel result, Void attachment) {
                try {
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    buffer.put("服务端 TO 客户端 ：say hello".getBytes());
                    buffer.flip();
                    result.write(buffer, null, new CompletionHandler<Integer, Void>(){
                        @Override
                        public void completed(Integer result, Void attachment) {
                            System.out.println("服务端发送消息成功");
                        }

                        @Override
                        public void failed(Throwable exc, Void attachment) {
                            System.out.println("发送失败");
                        }
                    });

                    ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                    result.read(readBuffer, null, new CompletionHandler<Integer, Void>() {
                        //成功时调用
                        @Override
                        public void completed(Integer result, Void attachment) {
                            System.out.println("接收客户端消息：" + new String(readBuffer.array()));
                        }
                        //失败时调用
                        @Override
                        public void failed(Throwable exc, Void attachment) {
                            System.out.println("读取失败");
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //失败时
            @Override
            public void failed(Throwable exc, Void attachment) {
                exc.printStackTrace();
            }
        });
    }
}